package cn.xiaobai.config;

import com.alibaba.druid.pool.DruidDataSource;

import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * @Author yangdaji
 * @Date 2023/12/20
 * @PackageName cn.xiaobai.config
 * @ClassName MysqlConfig
 */
public class MysqlConfig {

    private static Logger log = Logger.getLogger(MysqlConfig.class.getName());

    private static DruidDataSource dataSource = null;

    public MysqlConfig() {
        init();
    }

    private void init() {
        Properties properties = new Properties();
        URL resource = ClassLoader.getSystemClassLoader().getResource("db.properties");
        try {
            if (resource != null) {
                Path path = Paths.get(resource.toURI());
                properties.load(Files.newBufferedReader(path));
            } else {
                // 从当前目录获取
                Path path = Paths.get("db.properties");
                properties.load(Files.newBufferedReader(path));
            }
            dataSource = new DruidDataSource();
            dataSource.configFromPropeties(properties);
        } catch (Exception e) {

        }
    }

    public static MysqlConfig getInstance() {
        return new MysqlConfig();
    }

    public Connection getConn() {
        try {
            return dataSource.getConnection();
        } catch (Exception e) {
            log.warning("conn fail: " + e.getMessage());
            return null;
        }
    }


    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
